﻿using Common;
using Dapr.Actors.Runtime;
using System.Text.Json;

namespace BackEnd.Actors;

public class WorkflowActor : Actor, IWorkflowActor, IRemindable
{
    private readonly ILogger<WorkflowActor> _logger;

    public WorkflowActor(ActorHost host, ILogger<WorkflowActor> logger) : base(host)
    {
        _logger = logger ?? throw new ArgumentNullException(nameof(host));
        //_logger = logger;
    }

    public async Task<bool> ApproveAsync()
    {
        await StateManager.AddOrUpdateStateAsync(Id.ToString(), "approve", (key, currentStatus) => "approve");
        return true;
    }

    private static readonly string stateName = "counter";
    public async Task<int> IncrementAsync()
    {
        var counterValue = await StateManager.TryGetStateAsync<int>(stateName);
        var currentValue = counterValue.HasValue ? counterValue.Value : 0;
        var newValue = currentValue + 1;
        await StateManager.SetStateAsync(stateName, newValue);

        return newValue;
    }

    #region Timer
    private static readonly string timeName = "TestTimer";

    public Task RegisterTimerAsync()
    {
        var serializedTimerParams = JsonSerializer.SerializeToUtf8Bytes($"now is {DateTime.Now}");
        return RegisterTimerAsync(timeName, nameof(this.TimerCallbackAsync), serializedTimerParams, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3));
    }

    private async Task TimerCallbackAsync(byte[] data)
    {
        var stateKey = "timer-nowtime";
        var content = JsonSerializer.Deserialize<string>(data);
        _logger.LogInformation($"[{DateTime.Now}] timer content=> {content}");
        await StateManager.SetStateAsync<string>(stateKey, content);
    }

    public Task UnregisterTimerAsync()
    {
        return UnregisterTimerAsync(timeName);
    }
    #endregion

    #region Reminder
    private static readonly string reminderName = "TestReminder";

    public async Task RegisterReminderAsync()
    {
        var state = JsonSerializer.SerializeToUtf8Bytes($"now is {DateTime.Now}");
        await RegisterReminderAsync(reminderName, state, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(3));
    }

    // 异步接收提醒 Reminder 
    public async Task ReceiveReminderAsync(string reminderName, byte[] state, TimeSpan dueTime, TimeSpan period)
    {
        var stateKey = "reminder-nowtime";
        var content = JsonSerializer.Deserialize<string>(state);
        _logger.LogInformation($"[{DateTime.Now}] reminder content ==> {content}");
        await StateManager.SetStateAsync<string>(stateKey, content);
    }

    public Task UnregisterReminderAsync()
    {
        return base.UnregisterReminderAsync(reminderName);
    }
    #endregion

}